package com.dlyk.controller;

import com.dlyk.bean.TClue;
import com.dlyk.query.ClueQuery;
import com.dlyk.result.R;
import com.dlyk.service.ClueService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 线索管理
 */
@Slf4j
@RestController
public class ClueController {

    @Autowired
    private ClueService clueService;

    /**
     * 线索管理分页查询
     * @param current
     * @return
     */
    @PreAuthorize("hasAuthority('clue:list')")
    @GetMapping("/api/clues")
    public R cluePage(@RequestParam("current") Integer current){
        if (current==null){
            current=1;
        }
        PageInfo<TClue> pageInfo=clueService.getClueByPage(current);
        return R.OK(pageInfo);
    }

    /**
     * 导入Excel文件
     * @param file
     * @return
     */
    @PreAuthorize("hasAuthority('clue:import')")
    @PostMapping("/api/importExcel")
    public R importExcel(MultipartFile file,@RequestHeader("Authorization") String token) throws IOException {
        clueService.importExcel(file.getInputStream(),token);
        return R.OK();
    }

    /**
     * 验证手机号是否存在
     * @param phone
     * @return
     */
    @GetMapping("/api/clue/{phone}")
    public R getPhone(@PathVariable String phone){
        Boolean checkPhone=clueService.getPhone(phone);
        return checkPhone ? R.OK() : R.FAIL();
    }

    /**
     * 录入线索
     * @param clueQuery
     * @param token
     * @return
     */
    @PreAuthorize("hasAuthority('clue:add')")
    @PostMapping("/api/clue")
    public R clueSubmit(ClueQuery clueQuery,@RequestHeader("Authorization") String token){
        clueQuery.setToken(token);
        int save=clueService.save(clueQuery);
        return save>0 ? R.OK():R.FAIL();
    }

    /**
     * 根据id查询线索详情
     * @param id
     * @return
     */
    @PreAuthorize("hasAuthority('clue:view')")
    @GetMapping("/api/clue/detail/{id}")
    public R loadClue(@PathVariable Integer id){
        TClue clue=clueService.getClueById(id);
        return R.OK(clue);
    }

    /**
     * 修改线索数据
     * @param clueQuery
     * @param token
     * @return
     */
    @PreAuthorize("hasAuthority('clue:edit')")
    @PutMapping("/api/clue")
    public R editClue(ClueQuery clueQuery,@RequestHeader("Authorization") String token){
        clueQuery.setToken(token);
        int updateClue=clueService.updateClue(clueQuery);
        return updateClue> 0 ? R.OK():R.FAIL();
    }

    /**
     * 删除线索
     * @param id
     * @return
     */
    @PreAuthorize("hasAuthority('clue:delete')")
    @DeleteMapping("/api/clue/{id}")
    public R delClue(@PathVariable Integer id){
        int count=clueService.deleteClue(id);
        return count>0 ?R.OK():R.FAIL();
    }
}
